package com.startx.http.system.tool;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import com.startx.http.system.constant.Constants;

/**
 * 响应包装实现
 * @author minghu.zhang
 */
public class ResponseBuilder {
	
	/**
	 * http 成功响应
	 */
	private static final HttpResponse SUCCESSFUL = new HttpResponse().build(Code.SUCCESSFUL).build(Constants.EMPTY_DICTIONARY); 

	/**
	 * 创建响应对象
	 * @return
	 */
	public static HttpResponse successful() {
		return SUCCESSFUL;
	}
	
	/**
	 * 创建响应对象
	 * @return
	 */
	public static HttpResponse build(Object data) {
		return new HttpResponse()
				.build(Code.SUCCESSFUL)
				.build(data);
	}
	
	/**
	 * 创建响应对象
	 * @return
	 */
	public static HttpResponse build(Map<String,Object> data) {
		return new HttpResponse()
				.build(Code.SUCCESSFUL)
				.build(data);
	}
	
	/**
	 * 创建响应对象
	 * @return
	 */
	public static HttpResponse build(String key,Object value) {
		return new HttpResponse()
				.build(Code.SUCCESSFUL)
				.build(key,value);
	}
	
	/**
	 * 创建响应对象
	 * @return
	 */
	public static HttpResponse build(Code code,Map<String,Object> data) {
		return new HttpResponse()
				.build(code)
				.build(data);
	}
	
	/**
	 * 创建响应对象
	 * @return
	 */
	public static HttpResponse build(Code code) {
		return new HttpResponse()
				.build(code)
				.build(Constants.EMPTY_DICTIONARY);
	}

	/**
	 * Http响应对象
	 * @author minghu.zhang
	 */
	public static class HttpResponse {
		
		private Map<String, Object> code = new HashMap<>();
		private Object data;
		
		public Map<String, Object> getCode() {
			return code;
		}

		public Object getData() {
			return data;
		}

		private HttpResponse build(Code code) {
			this.code.putAll(code.value);
			return this;
		}
		
		@SuppressWarnings("unchecked")
		public HttpResponse build(String key,Object value) {
			if(Objects.isNull(data)) {
				data = new HashMap<>();
			}
			
			Map<String,Object> ags = (Map<String, Object>) data;
			ags.put(key, value);
			
			return this;
		}
		
		public HttpResponse build(Object data) {
			this.data = data;
			return this;
		}
		
		private HttpResponse() {}
	}

	/**
	 * 响应码和响应消息
	 * 
	 * @author minghu.zhang
	 */
	public static enum Code {
		SUCCESSFUL(200,"successful"),
		BAD_REQUEST(401,"bad request"),
		FAILURE(403,"failure"),
		NOT_FOUND(404,"not found"),
		TIMEOUT(408,"login timeout"),
		SERVICE_EXPIRE(503,"service expire"),
		FORBIDDEN_LOGIN(505,"FORBIDDEN_LOGIN");
		/**
		 * 转json值
		 */
		private Map<String,Object> value = new HashMap<>();

		private Code(int code, String msg) {
			value.put("code", code);
			value.put("msg", msg);
		}

		public Map<String, Object> getValue() {
			return value;
		}

		public void setMsg(String msg) {
			value.put("msg", msg);
		}
	}

}
